import 'package:flutter/material.dart';
import 'dart:convert';

import '../services/storage.dart';

class Cart with ChangeNotifier{

  final key = 'cartList';

  /// 购物车列表
  List _cartList = [];
  /// 全选
  bool _isCheckedAll = false;
  /// 总价
  double _allPrice = 0;

  List get cartList => _cartList;
  bool get isCheckedAll => _isCheckedAll;
  double get allPrice => _allPrice;
  
  Cart() {
    init();
  }

  /// 初始化的时候获取数据
  init() async{
    try {
      List cartList = json.decode(await Storage.getString(key));
      _cartList = cartList;
    } catch(e) {
      _cartList = [];
    }
    ///获取全选的状态
    _isCheckedAll = isCheckAll();
    computeAllPrice(); //计算总价
    notifyListeners();
  }

  /// 更新数据
  updateList() {
    init();
  }

  /// 保存商品数量
  itemCountChange() {
    computeAllPrice(); //计算总价
    Storage.setString(key, json.encode(_cartList));
    notifyListeners();
  }

  /// 全选、反选
  checkAll(value) {
    for(var i=0;i<_cartList.length;i++) {
      _cartList[i]['checked'] = value;
    }
    _isCheckedAll = value;
    computeAllPrice(); //计算总价

    Storage.setString(key, json.encode(_cartList));
    notifyListeners();
  }

  /// 判断是否全选
  bool isCheckAll() {
    if(_cartList.isNotEmpty) {
      for(var i=0;i<_cartList.length;i++) {
        if(_cartList[i]['checked'] == false) {
          return false;
        }
      }
      return true;
    } else {
       return false;
    }
    
  }

  /// 监听每一项的选中事件
  itemChange() {
    if(isCheckAll()){
      _isCheckedAll = true;
    } else {
      _isCheckedAll = false;
    }
    computeAllPrice(); //计算总价
    Storage.setString(key, json.encode(_cartList));
    notifyListeners();
  }

  /// 计算总价
  computeAllPrice() {
    double tempAllPrice = 0;
    for(var i=0;i<_cartList.length;i++) {
      if(_cartList[i]['checked']) {
        tempAllPrice += _cartList[i]['price'] * _cartList[i]['count'];
      }
    }
    _allPrice = tempAllPrice;
    notifyListeners();
  }

  /// 删除购物车数据
  removeItem() {
    List tempList = [];
    for(var i=0;i<_cartList.length;i++) {
      if(!_cartList[i]['checked']) {
        tempList.add(_cartList[i]);
      }
    }

    _cartList = tempList;
    computeAllPrice(); //计算总价
    
    Storage.setString(key, json.encode(_cartList));
    notifyListeners();
  }

}